<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle()" width="900px" @ok="handleOk" destroyOnClose>
    <MessageForm ref="form1"></MessageForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, useAttrs, getCurrentInstance, nextTick } from 'vue';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import MessageForm from './MessageForm.vue';
// 声明Emits
const emit = defineEmits(['success', 'register']);
const attrs = useAttrs();
//是否是更新模式
const isUpdate = ref(true);
//是否显示底部按钮
const showFooter = ref(true);
//当前选中tab
const activeKey = ref('form1');
//当前选中对象
const selectData = ref();
const ctx: any = getCurrentInstance();
//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  activeKey.value = 'form1';
  isUpdate.value = !!data?.isUpdate;
  //设置是否显示底部
  setDrawerProps({ confirmLoading: false, showFooter: true });
  selectData.value = data;
  handleTabChange();
});

/**
 * 获取标题
 */
function getTitle() {
  return !isUpdate.value ? '新增消息' : '编辑消息';
}

/**
 * tab切换事件
 */
function handleTabChange() {
  nextTick(() => {
    ctx.refs[activeKey.value].setData(selectData.value);
  });
}

/**
 * 确定按钮事件
 */
async function handleOk() {
  try {
    setDrawerProps({ confirmLoading: true });
    ctx.refs[activeKey.value].handleSubmit((callback) => {
      //执行子组件回调事件
      callback && callback(emit);
      //关闭抽屉
      closeDrawer();
    });
  } catch (err) {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
